var express = require('express')
var path = require('path')
var cookieParser = require('cookie-parser')
var logger = require('morgan')
const cors = require('cors')
const jwtCheck = require('./middleware/jwtCheck')
const blacklistCheck = require('./middleware/blacklistCheck')
const refreshToken = require('./middleware/refreshToken')
const addSuccessMethod = require('./middleware/addSuccessMethod')
var compression = require("compression");
const history = require("connect-history-api-fallback");
const errMessge = require('./enum/errMessge')
const router = require('./routes')
var app = express()
app.use(compression({ threshold: 1024 }));
// 允许跨域资源共享
app.use(
  cors({
    origin: true, //true 设置为 req.origin.url
    methods: "GET,HEAD,PUT,PATCH,POST,DELETE", //容许跨域的请求方式
    allowedHeaders: "x-requested-with,Authorization,token, content-type", //跨域请求头
    exposedHeaders: "Authorization", //跨域响应头
    preflightContinue: false, // 是否通过next() 传递options请求 给后续中间件
    maxAge: 1728000, //options预验结果缓存时间 20天
    credentials: true, //携带cookie跨域
    optionsSuccessStatus: 200, //options 请求返回状态码
  })
);
app.use(logger("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, "public")));
app.use(express.static(path.join(__dirname, "uploads")));
// 使用自定义中间件
// 挂载路由
app.use("/api", addSuccessMethod(), jwtCheck(), blacklistCheck, refreshToken, router);
// 使用 connect-history-api-fallback 中间件
app.use(
  history({
    verbose: true, // 可选，用于日志记录
  })
);
app.use(express.static(path.join(__dirname, "dist")));
// catch 404 and forward to error handler
app.use(function (req, res, next) {
  res.send({ code: 404, message: 'Not Found' })
})

// error handler
app.use(function (err, req, res, next) {
  console.log('------err------: ', err, '-', err.message, '-', err.status)
  res.status(err.status || 500).json({
    // err对象属性属于原型上的成员，而json只能将对象本身的成员序列化到字符串
    code: err.status || 500,
    message: errMessge[err.message] || '请求参数错误',
  })
})

module.exports = app
